import React, { useState, useEffect } from 'react';
import { Upload, Button, Table, InputNumber, message, Form, Input, Select} from 'antd';
import { UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import { Problem, TestCaseScore } from '@/types/problem';
import { problemService } from '@/services/problemService';
import styles from './TestCaseForm.module.css';

interface TestCaseFormProps {
  initialValues?: Partial<Problem>;
  onSubmit: (values: any) => void;
}

const { Option } = Select;

const TestCaseForm: React.FC<TestCaseFormProps> = ({ initialValues, onSubmit }) => {
  const [testCases, setTestCases] = useState<TestCaseScore[]>(
    initialValues?.test_case_score || []
  );
  const [testCaseId, setTestCaseId] = useState<string>(
    initialValues?.test_case_id || ''
  );
  const [ioMode, setIoMode] = useState(initialValues?.io_mode?.io_mode || 'Standard IO');
  const [form] = Form.useForm();

  useEffect(() => {
    form.setFieldsValue({
      io_mode: initialValues?.io_mode || { io_mode: 'Standard IO' },
    });
  }, [initialValues]);

  useEffect(() => {
    if (initialValues?.test_case_score) {
      setTestCases(initialValues.test_case_score);
    }
    if (initialValues?.test_case_id) {
      setTestCaseId(initialValues.test_case_id);
    }
  }, [initialValues]);

  const columns = [
    {
      title: '输入文件',
      dataIndex: 'input_name',
      key: 'input_name',
    },
    {
      title: '输出文件',
      dataIndex: 'output_name',
      key: 'output_name',
    },
    {
      title: '分数',
      dataIndex: 'score',
      key: 'score',
      render: (text: number, _: TestCaseScore, index: number) => (
        <InputNumber
          min={0}
          max={100}
          value={text}
          onChange={(value) => handleScoreChange(index, value)}
        />
      ),
    },
  ];

  const handleScoreChange = (index: number, value: number | null) => {
    if (value === null) return;
    const newTestCases = [...testCases];
    newTestCases[index].score = value;
    setTestCases(newTestCases);
  };

  const handleUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    
    const formData = new FormData();
    formData.append('file', file);
    formData.append('spj', 'false');

    try {
      const response = await problemService.uploadTestCase(formData);
      
      if (response.data.data) {
        const { id, info } = response.data.data;
        setTestCaseId(id);

        // 为每个测试用例设置均分
        const averageScore = Math.floor(100 / info.length);
        const testCaseScores = info.map(item => ({
          input_name: item.input_name,
          output_name: item.output_name,
          score: averageScore,
        }));

        // 如果有余数，将其加到最后一个测试用例
        const remainder = 100 - averageScore * info.length;
        if (remainder > 0 && testCaseScores.length > 0) {
          testCaseScores[testCaseScores.length - 1].score += remainder;
        }

        setTestCases(testCaseScores);
        message.success('测试用例上传成功');
        onSuccess();
      } else {
        throw new Error('上传失败');
      }
    } catch (error) {
      message.error('测试用例上传失败');
      onError();
    }
  };

  const handleDownloadTestCase = async () => {
    if (!initialValues?.id) {
      message.error('题目ID不存在，无法下载测试样例');
      return;
    }

    try {
      const response = await problemService.downloadTestCase(initialValues.id);
      
      // 创建下载链接
      const blob = new Blob([response.data as unknown as Blob], { type: 'application/zip' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `testcase_${initialValues.id}.zip`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.success('测试样例下载成功');
    } catch (error) {
      console.error('下载测试样例失败:', error);
      message.error('下载测试样例失败');
    }
  };

  const handleSubmit = () => {
    // 先验证表单
    form.validateFields().then(async (values) => {
      if (testCases.length === 0) {
        message.error('请先上传测试用例');
        return;
      }

      const totalScore = testCases.reduce((sum, tc) => sum + tc.score, 0);
      if (totalScore !== 100) {
        message.error('所有测试用例的分数之和必须为100');
        return;
      }

      const ioModeData = values.io_mode.io_mode === 'File IO' 
        ? {
            io_mode: 'File IO',
            input: values.io_mode.input,
            output: values.io_mode.output,
          }
        : { io_mode: 'Standard IO' };

      onSubmit({
        test_case_id: testCaseId,
        test_case_score: testCases,
        io_mode: ioModeData,
      });
    }).catch(() => {
      // 验证失败会自动显示错误信息
    });
  };

  return (
    <div className={styles.container}>
      <Form form={form} layout="vertical">
        <Form.Item
          name={['io_mode', 'io_mode']}
          label="IO模式"
          rules={[{ required: true }]}
        >
          <Select onChange={(value) => setIoMode(value)}>
            <Option value="Standard IO">标准IO</Option>
            <Option value="File IO">文件IO</Option>
          </Select>
        </Form.Item>

        {ioMode === 'File IO' && (
          <div className={styles.fileIoInputs}>
            <Form.Item
              name={['io_mode', 'input']}
              label="输入文件名"
              rules={[{ required: true, message: '请输入输入文件名' }]}
            >
              <Input placeholder="例如: a.in" />
            </Form.Item>
            <Form.Item
              name={['io_mode', 'output']}
              label="输出文件名"
              rules={[{ required: true, message: '请输入输出文件名' }]}
            >
              <Input placeholder="例如: a.out" />
            </Form.Item>
          </div>
        )}

        <div className={styles.uploadSection}>
          <div className={styles.uploadActions}>
            <Upload
              customRequest={handleUpload}
              showUploadList={true}
              accept=".zip"
              maxCount={1}
            >
              <Button icon={<UploadOutlined />}>上传测试用例</Button>
            </Upload>
            
            {initialValues?.id && (
              <Button 
                icon={<DownloadOutlined />} 
                onClick={handleDownloadTestCase}
                className={styles.downloadButton}
              >
                下载测试样例
              </Button>
            )}
          </div>
          <p className={styles.hint}>
            请将所有测试用例打包成zip文件上传，文件名格式为：1.in, 1.out, 2.in, 2.out...
          </p>
        </div>

        {testCases.length > 0 && (
          <>
            <Table
              columns={columns}
              dataSource={testCases}
              rowKey="input_name"
              pagination={false}
              className={styles.table}
            />
            <div className={styles.totalScore}>
              总分：{testCases.reduce((sum, tc) => sum + tc.score, 0)}/100
            </div>
          </>
        )}

        <div className={styles.actions}>
          <Button type="primary" onClick={handleSubmit}>
            下一步
          </Button>
        </div>
      </Form>
    </div>
  );
};

export default TestCaseForm; 